package org.example.netty.protocol;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.protobuf.ProtobufDecoder;
import io.netty.handler.codec.protobuf.ProtobufVarint32FrameDecoder;
import io.netty.util.concurrent.DefaultEventExecutorGroup;
import io.netty.util.concurrent.EventExecutorGroup;
import org.example.netty.handler.CustomProtobufDecoder;
import org.example.netty.handler.ProtobufBusinessHandler;
import org.example.utils.LogUtils;

public class CustomProtobufServer {
    public static void main(String[] args) {
        ServerBootstrap bootstrap = new ServerBootstrap();

        // 定义父子反应器
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        bootstrap.localAddress(8081);
        // 设置为异步NIO
        bootstrap.channel(NioServerSocketChannel.class);
        bootstrap.group(bossGroup, workerGroup);

        bootstrap.option(ChannelOption.SO_KEEPALIVE, true);

        // 单独创建一个线程组，创建一个32线程的线程组
        final EventExecutorGroup executorA = new DefaultEventExecutorGroup(32);

        bootstrap.childHandler(new ChannelInitializer<SocketChannel>() {
            @Override
            protected void initChannel(SocketChannel ch) throws Exception {
                // 长度解码要单独处理
                ch.pipeline().addLast(new CustomProtobufDecoder());
                // 内容解码
                ch.pipeline().addLast(new ProtobufDecoder(MsgProtos.Msg.getDefaultInstance()));
                // 打印内容
                ch.pipeline().addLast(executorA, new ProtobufBusinessHandler());
            }
        });
        
        try {
            // 等待服务端绑定成功
            ChannelFuture future = bootstrap.bind().sync();

            LogUtils.info("服务端启动成功");
            // 获取对应的通道
            Channel channel = future.channel();

            // 等待关闭
            channel.closeFuture().sync();
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        finally {
            // 优雅的进行关闭
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
